"""
自动选品对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                           QComboBox, QPushButton, QSpinBox,
                           QFrame, QMessageBox)
from PyQt6.QtCore import Qt
from biz.script_runner import get_script_runner
from gui.widgets.auto_select_worker import AutoSelectWorker
from com.constants.wear_ranges import (WearCategory, get_category_name, 
                                     WEAR_CATEGORY_RANGES, WearRange,
                                     get_wear_ranges)

class AutoSelectDialog(QDialog):
    """自动选品对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("设置自动选品筛选条件")
        self.setMinimumWidth(400)
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        
        # 外观选择
        wear_layout = QHBoxLayout()
        wear_label = QLabel("外观:")
        self.wear_combo = QComboBox()
        # 添加外观选项
        for category in WearCategory:
            self.wear_combo.addItem(get_category_name(category), category.value)
        
        wear_layout.addWidget(wear_label)
        wear_layout.addWidget(self.wear_combo)
        layout.addLayout(wear_layout)
        
        # 磨损值范围
        wear_range_layout = QHBoxLayout()
        wear_range_label = QLabel("磨损值范围:")
        
        # 磨损值范围下拉框
        self.wear_range_combo = QComboBox()
        wear_range_layout.addWidget(wear_range_label)
        wear_range_layout.addWidget(self.wear_range_combo)
        layout.addLayout(wear_range_layout)
        
        # 价格范围
        price_layout = QHBoxLayout()
        price_label = QLabel("价格范围:")
        self.min_price_spin = QSpinBox()
        self.min_price_spin.setRange(0, 999999)
        
        price_separator = QLabel("-")
        
        self.max_price_spin = QSpinBox()
        self.max_price_spin.setRange(0, 999999)
        
        price_layout.addWidget(price_label)
        price_layout.addWidget(self.min_price_spin)
        price_layout.addWidget(price_separator)
        price_layout.addWidget(self.max_price_spin)
        layout.addLayout(price_layout)
        
        # 最低销售数量
        min_sales_layout = QHBoxLayout()
        min_sales_label = QLabel("最低销售数量:")
        self.min_sales_spin = QSpinBox()
        self.min_sales_spin.setRange(0, 999999)
        self.min_sales_spin.setValue(500)  # 默认值500
        
        min_sales_layout.addWidget(min_sales_label)
        min_sales_layout.addWidget(self.min_sales_spin)
        layout.addLayout(min_sales_layout)
        
        # 溢价率
        premium_layout = QHBoxLayout()
        premium_label = QLabel("溢价率:")
        self.premium_spin = QSpinBox()
        self.premium_spin.setRange(0, 100)
        self.premium_spin.setValue(10)  # 默认值10%
        self.premium_spin.setSuffix("%")
        
        premium_layout.addWidget(premium_label)
        premium_layout.addWidget(self.premium_spin)
        layout.addLayout(premium_layout)
        
        # 溢价率提示
        tip_label = QLabel("(溢价率即目标标签的售价比正常售价高出的百分比，溢价率越高收益越高)")
        tip_label.setStyleSheet("color: #909399; font-size: 12px;")
        layout.addWidget(tip_label)
        
        # 按钮
        button_layout = QHBoxLayout()
        self.start_button = QPushButton("开始")
        self.cancel_button = QPushButton("取消")
        
        button_layout.addWidget(self.start_button)
        button_layout.addWidget(self.cancel_button)
        layout.addLayout(button_layout)
        
        # 绑定信号
        self.wear_combo.currentIndexChanged.connect(self.on_wear_changed)
        self.start_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        
        # 设置默认值
        self.on_wear_changed(0)
        
    def _get_wear_range_text(self, wear_range: WearRange) -> str:
        """获取磨损值范围的显示文本"""
        return wear_range.show_name
        
    def on_wear_changed(self, index):
        """外观选择改变时更新磨损值范围选项"""
        category = WearCategory(self.wear_combo.currentData())
        
        # 清空并添加新的磨损值范围选项
        self.wear_range_combo.clear()
        
        # 只添加细分区间
        for subrange in get_wear_ranges(category):
            self.wear_range_combo.addItem(
                self._get_wear_range_text(subrange),
                (subrange.min_val, subrange.max_val)
            )
        
    def accept(self):
        """确认按钮点击事件"""
        try:
            # 获取筛选条件
            category = WearCategory(self.wear_combo.currentData())
            min_wear, max_wear = self.wear_range_combo.currentData()
            min_price = self.min_price_spin.value()
            max_price = self.max_price_spin.value()
            min_sales = self.min_sales_spin.value()
            premium_rate = self.premium_spin.value()
            
            # 创建筛选条件
            filter_condition = {
                'wear_type': category.value,
                'min_wear': min_wear,
                'max_wear': max_wear,
                'min_price': min_price,
                'max_price': max_price,
                'min_count': min_sales,  
                'premium_rate': premium_rate
            }
            
            # 创建 worker 并返回给页面
            self.worker = AutoSelectWorker(filter_condition)
            
            # 关闭对话框
            super().accept()
            
        except Exception as e:
            QMessageBox.warning(self, "错误", f"设置筛选条件失败: {str(e)}")
            
    def get_worker(self) -> AutoSelectWorker:
        """获取创建的 worker"""
        return self.worker
        
    def reset_values(self):
        """重置所有值为默认值"""
        self.wear_combo.setCurrentIndex(0)
        self.wear_range_combo.setCurrentIndex(0)
        self.min_price_spin.setValue(5)
        self.max_price_spin.setValue(100)
        self.min_sales_spin.setValue(500)
        self.premium_spin.setValue(10)
        
    def get_values(self) -> dict:
        """获取所有设置的值"""
        min_wear, max_wear = self.wear_range_combo.currentData()
        return {
            'wear': self.wear_combo.currentText(),
            'min_wear': min_wear,
            'max_wear': max_wear,
            'min_price': self.min_price_spin.value(),
            'max_price': self.max_price_spin.value(),
            'min_sales': self.min_sales_spin.value(),
            'premium_rate': self.premium_spin.value()
        }
